package cn.finder.datatunnel;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class HttpUtils {

	/***
	 * 
	 * 直接发送POST数据 HTTP形式
	 * 
	 * @param url
	 * @param data
	 * @return
	 */
	public String doPostData(String url, String data) {
		String returnStr = "{}";
		String strData = "";
		try {
			// strData = URLEncoder.encode(data, HTTP.UTF_8);
			strData = data;
		} catch (Exception e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		try {
			String CHARSET = "UTF-8";
			// 创建连接
			URL theurl = new URL(url);
			HttpURLConnection connection = (HttpURLConnection) theurl
					.openConnection();

			connection.setDoOutput(true);
			connection.setDoInput(true);
			connection.setRequestMethod("POST");
			connection.setUseCaches(false);
			connection.setInstanceFollowRedirects(true);
			connection.setRequestProperty("Content-Type",
					"application/x-www-form-urlencoded");
			connection.setRequestProperty("Charset", CHARSET);

			connection.connect();

			// POST请求
			DataOutputStream out = new DataOutputStream(
					connection.getOutputStream());

			out.write(strData.getBytes("utf-8"));
			out.flush();
			out.close();

			// 读取响应
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					connection.getInputStream()));
			String lines;
			StringBuffer sb = new StringBuffer("");
			while ((lines = reader.readLine()) != null) {
				lines = new String(lines.getBytes(), "utf-8");
				sb.append(lines);
				sb.append("\n");// 换行 需要加上 update by 20150928
			}
			// System.out.println(sb);
			returnStr = sb.toString();
			reader.close();
			// 断开连接
			connection.disconnect();
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return returnStr;
	}
}
